'use strict';
var https = require('https')
var _ = require('lodash')
function post(options, postData, log) {
  return new Promise(function(resolve, reject) {
    var req = https.request(options, function(res) {
      res.setEncoding('utf8');
      var json = ''
      res.on('data', function (chunk) {
        json += chunk;
      });
      res.on('end', function() {
        // 由于userId长度超过17位，需要操作responseText
        resolve(json)
      })
    })
    req.on('error', function (e) {
      console.log('problem with request: ' + e.message);
      reject(e)
    })
    req.write(postData);
    req.end();
  })
}

function getUserId(resText) {
  var reg = /\"userId\":(\s*|\s+)\d+/;
  var arr = resText.match(reg);
  var userId = arr[0].split(":")[1].trim();
  return userId;
}

// 找到userId，变成字符串后输出
function formatRes(res) {
  if (res.indexOf('"userId":') === -1) {
    return JSON.parse(res)
  } else {
    var userId = getUserId(res)
    res = JSON.parse(res)
    _.set(res, 'result.userId', userId);
    return res
  }
}

module.exports.post = post
module.exports.formatRes = formatRes